package org.yang.loginunion.core.qq;

import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.yang.loginunion.core.LoginClient;
import org.yang.loginunion.core.constants.IdentityType;
import org.yang.loginunion.core.exception.LoginException;
import org.yang.loginunion.core.model.BindAuthCode;
import org.yang.loginunion.core.qq.model.TokenOpenid;
import org.yang.loginunion.core.qq.model.UserInfo;
import org.yang.loginunion.core.qq.request.IQQRequest;
import org.yang.loginunion.core.repository.OauthRepository;
import org.yang.loginunion.core.repository.OauthTempRepository;

import java.util.ArrayList;
import java.util.Optional;

/**
 * QQ授权登录
 *
 * @author Billyang
 * @date 2024/8/12 14:40
 */
public class QQClient implements LoginClient {

    private OauthRepository oauthRepository;
    private OauthTempRepository oauthTempRepository;
    private IQQRequest qqRequest;

    public QQClient(OauthRepository oauthRepository, OauthTempRepository oauthTempRepository, IQQRequest qqRequest) {
        this.oauthRepository = oauthRepository;
        this.oauthTempRepository = oauthTempRepository;
        this.qqRequest = qqRequest;
    }

    /**
     * <pre>
     * 官网（Step2：通过Authorization Code获取Access Token）：https://wiki.connect.qq.com/%e4%bd%bf%e7%94%a8authorization_code%e8%8e%b7%e5%8f%96access_token
     * </pre>
     */
    @Override
    public String login(String ignore1, String redirectUri, String code) {
        if(StringUtils.isBlank(code)){
            throw new LoginException("缺失参数");
        }

        TokenOpenid tokenOpenid  = qqRequest.token(code, redirectUri);
        String openid = tokenOpenid.getOpenid();
        if(StringUtils.isBlank(openid)){
            openid = qqRequest.getOpenid(tokenOpenid.getAccessToken());
        }

        UserInfo userInfo = qqRequest.getUserInfo(tokenOpenid.getAccessToken(), openid);
         // 根据openid查询user_id
        String userId = oauthRepository.getUserId(IdentityType.QQ_OPENID, openid);

        if(userId == null){
            BindAuthCode bindAuthCode = new BindAuthCode();
            bindAuthCode.setNickname(Optional.ofNullable(userInfo).map(UserInfo::getNickname).orElse(null));
            bindAuthCode.setHeadimgurl(Optional.ofNullable(userInfo).map(UserInfo::getHeadImgUrl).orElse(null));
            ArrayList<BindAuthCode.BindUserOauth> binds = Lists.newArrayList();
            binds.add(new BindAuthCode.BindUserOauth().setIdentityType(IdentityType.QQ_OPENID).setIdentifier(openid));
            bindAuthCode.setBinds(binds);

            oauthTempRepository.saveBindAuthCode(openid, bindAuthCode);

            // QQ没有绑定账号
            return null;
        }
        return userId;
    }
}
